package com.cysion.study.ui

import android.graphics.Bitmap
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.ChooseKnowListAdapter
import com.cysion.study.entity.XitiListEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.BasePicActivity
import com.cysion.study.widget.FlowLayoutForPulish
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.http.HttpUtil
import com.cysion.targetfun._subscribe
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import kotlinx.android.synthetic.main.activity_comment_detail.*
import kotlinx.android.synthetic.main.activity_feedback.*
import kotlinx.android.synthetic.main.activity_modify_answer_ti.*
import kotlinx.android.synthetic.main.activity_modify_answer_ti.fl_pics
import kotlinx.android.synthetic.main.activity_modify_answer_ti.topbar
import kotlinx.android.synthetic.main.activity_modify_answer_ti.tv_submit
import org.json.JSONObject
import java.io.File
import java.util.*

//编辑解答题
class ModifyAnswerTiActivity : BasePicActivity() {
    override fun getLayoutId(): Int = R.layout.activity_modify_answer_ti
    private lateinit var dataAdapter: ChooseKnowListAdapter
    private val dataList: MutableList<String> = mutableListOf()
    private var curPage = 1
    private var courseId = ""
    private var pageType = ""
    private var obj: XitiListEntity? = null
    override fun initView() {
        courseId = intent.extras.getString("courseId")
        pageType = intent.extras.getString("type")
        whiteTextTheme(color(R.color.main_cl))
         topbar.apply {
             //1编辑，2新增
             if (pageType == "1") {
                 setTitle("编辑解答题")
                 obj = intent.extras.getSerializable("obj") as XitiListEntity?
                 modify()
             } else {
                 setTitle("添加解答题")
             }
//            setTexts("添加", TopBar.Pos.RIGHT)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }else if (pos == TopBar.Pos.RIGHT) {
//                    startActivity_ex<AddKnowActivity>()//添加习题与知识

                    /*AlertSearch.search(self,""){ confirm: Int, start: String, end: String ->
                        CLog.i("@@@搜索="+start+end)
                        curPage=1
                        getDataList(curPage,start,end)
                    }*/
                }
            }
        }
        tv_submit.setOnClickListener {
            submit()
        }
        initFlowLayoutForPulishListener()
    }

    private val selectPics = ArrayList<String>()
    private val answerPics = ArrayList<String>()
    private fun initFlowLayoutForPulishListener() {
//        fl_pics.setShow(false)
        fl_pics.setonFlowLayoutForPulishListener(object :
            FlowLayoutForPulish.OnFlowLayoutForPulishListener {
            override fun add() {
                if (selectPics.size >= 3) {
                    ShowToast("最多不能超过3张图片")
                    return
                }
                selectType="1"
                takePhoto()
            }

            override fun delete(item: FlowLayoutForPulish.Item) {
                selectPics.removeAt(item.index)
            }

            override fun onClick(item: FlowLayoutForPulish.Item) {
                val list = ArrayList<String>()
                list.add(item.path)
//                list.add(getFileUrl(item.path))
                //                PhotoPagerActivity.gotoActivity(_activity, list, 0);//预览大图
            }
        })
//        fl_pics.setShow(false)
        pics_as.setonFlowLayoutForPulishListener(object :
            FlowLayoutForPulish.OnFlowLayoutForPulishListener {
            override fun add() {
                if (answerPics.size >= 3) {
                    ShowToast("最多不能超过3张图片")
                    return
                }
                selectType="2"
                takePhoto()
            }

            override fun delete(item: FlowLayoutForPulish.Item) {
                answerPics.removeAt(item.index)
            }

            override fun onClick(item: FlowLayoutForPulish.Item) {
                val list = ArrayList<String>()
                list.add(item.path)
//                list.add(getFileUrl(item.path))
                //                PhotoPagerActivity.gotoActivity(_activity, list, 0);//预览大图
            }
        })
    }

    override fun outputBitmap(bitmap: Bitmap?, path: String?) {
        super.outputBitmap(bitmap, path)
        if (path != null) {
            if (selectType == "1") {
                uploadPic(path)
            } else {
                uploadAnswerPic(path)
            }
        }
    }

    private var selectType="1"//1题目，2答案

    private var ansIndex = 0
    private fun uploadAnswerPic(headUrl: String) {
        val params = RequestParams()
        params.put("file", File(headUrl))
        params.put("token", ACache.get(Box.context).getAsString("token"))
        HttpUtil.post1(Urls.uploadPicture, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out org.apache.http.Header>?, response: JSONObject?) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                try {
                    if (response?.getString("code") == "0") {
                        println("上传图片返回=${response.getString("data")}")
//                        var obj: String? = response.getString("data")
                        var imaPath = response.getString("data")
                        println("图片地址=${imaPath}")
                        answerPics.add(imaPath)//把图片添加到list
//                        pics_as.addLocationPic(ansIndex, false, headUrl)//显示图片
                        pics_as.setShowData(false,answerPics,false,true)
                        ansIndex++
                    } else {
                        ShowToast("上传失败")
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    Alert.close()
//                    ShowDialog.dissmiss()
                }
            }
            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(statusCode: Int, headers: Array<out org.apache.http.Header>?, responseString: String?, throwable: Throwable?) {
                super.onFailure(statusCode, headers, responseString, throwable)
                Alert.close()
            }
        })
    }



    private var index = 0
    private fun uploadPic(headUrl: String) {
        val params = RequestParams()
        params.put("file", File(headUrl))
        params.put("token", ACache.get(Box.context).getAsString("token"))
        HttpUtil.post1(Urls.uploadPicture, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out org.apache.http.Header>?, response: JSONObject?) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                try {
                    if (response?.getString("code") == "0") {
                        println("上传图片返回=${response.getString("data")}")
//                        var obj: String? = response.getString("data")
                        var imaPath = response.getString("data")
                        println("图片地址=${imaPath}")
                        selectPics.add(imaPath)//把图片添加到list
//                        fl_pics.addLocationPic(index, false, headUrl)//显示图片
                        fl_pics.setShowData(false,selectPics,false,true)
                        index++
                    } else {
                        ShowToast("上传失败")
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    Alert.close()
//                    ShowDialog.dissmiss()
                }
            }
            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(statusCode: Int, headers: Array<out org.apache.http.Header>?, responseString: String?, throwable: Throwable?) {
                super.onFailure(statusCode, headers, responseString, throwable)
                Alert.close()
            }
        })
    }

    private fun submit() {
        var title=et_title.text.toString().trim()
        var question=et_content.text.toString().trim()+"~~~"
        var answer=et_answer.text.toString().trim()
        var questionSB = StringBuilder()
        //答案选项 ，选项之间使用~~~分隔
        for (obj in selectPics) {
            question += obj+ "~~~"
        }
        /*if (pics.isNotEmpty()) {
            pics.deleteCharAt(0)
        }*/


        //@@@分隔各个答案
        for (obj in answerPics) {
            answer += obj + "@@@"
        }

        println("@@@@@="+question)

        var ifstore=""
        if (cb_item.isChecked) {
            ifstore = "1"
        }
        var id=""//知识点id，修改的时候必须传
        //type 2新加，1编辑
        if (pageType == "1") {
            id=obj?.id.toString()
        }
        Alert.loading(self)
         ApiClient.api.saveTi(id, courseId, question, answer, "4", ifstore, "试题详解内容", title, UserCache.token)
             .compose(BaseResponseRx.validateToMain())
             ._subscribe {
                 _onNext {
                     Alert.close()
                     ShowToast("保存成功")
                     finish()
                 }
                 _onError {
                     Alert.close()
                     ShowToast(ErrorHandler.handle(it).errorMsg)

                 }
             }
    }

    private fun modify() {
        et_title.setText(obj?.title)
        et_content.setText(obj?.question)
        et_answer.setText(obj?.answer)


    }

    //加载数据
    override fun initData() {
        super.initData()

    }





    private fun getDataList(page: Int, start: String, end: String) {
        Alert.loading(self)
        ApiClient.api.getTutorOrderList(UserCache.token,"",curPage.toString()).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()


                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }

    }




    override fun closeMvp() {
    }

}
